package net.wanglu.www.zzz.service.se.expl;

import java.util.HashMap;
import java.util.regex.Pattern;

import net.wanglu.www.zzz.service._Service;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.trees.TreeGraphNode;
import edu.stanford.nlp.trees.TypedDependency;
import edu.stanford.nlp.trees.tregex.TregexMatcher;
import edu.stanford.nlp.trees.tregex.TregexPattern;

public class CommonExplExtracter extends _Service {

	@Override
	public Object service(Object... objects) throws Exception {
		// TODO Auto-generated method stub
		HashMap<?, ?> preprocessData = (HashMap<?, ?>) objects[0];
		TypedDependency expl = (TypedDependency) objects[1];

		Tree root = (Tree) preprocessData.get("root");
		
		TregexPattern pattern = null;
		TregexMatcher matcher = null;
		/*
		 * 先行词与其祖先
		 */
		TreeGraphNode explGov = expl.gov();
		sb.clear();
		sb.append("/\\bVP\\b/");
		sb.append("<");
		sb.append("(");
		sb.append("/").append(Pattern.quote(explGov.label().tag())).append("/");
		sb.append("<");
		sb.append("/").append(Pattern.quote(explGov.label().word())).append("/");
		sb.append(")");
		pattern = TregexPattern.compile(sb.toString());
		matcher = pattern.matcher(root);
		Tree explGovAncestor = null;
		if ( matcher.find()) {
			explGovAncestor = matcher.getMatch();
		} else {
			explGovAncestor = explGov;
		}
		/*
		 * 动词及其祖先
		 */
		TreeGraphNode explDep = expl.dep();
		sb.clear();
		sb.append("/\\bNP\\b/");
		sb.append("<");
		sb.append("(");
		sb.append("/").append(Pattern.quote(explDep.label().tag())).append("/");
		sb.append("<");
		sb.append("/").append(Pattern.quote(explDep.label().word())).append("/");
		sb.append(")");	
		pattern = TregexPattern.compile(sb.toString());
		matcher = pattern.matcher(root);
		Tree explDepAncestor = null;
		if ( matcher.find()) {
			explDepAncestor = matcher.getMatch();
		} else {
			explDepAncestor = explDep;
		}

		
		final TreeGraphNode fexplGov = explGov;
		final Tree fexplGovAncestor = explGovAncestor;
		final TreeGraphNode fexplDep = explDep;
		final Tree fexplDepAncestor = explDepAncestor;
		
		return new _ExplTuple() {
			{
				this.setExplDep(fexplDep);
				this.setExplDepAncestor(fexplDepAncestor);
				this.setExplGov(fexplGov);
				this.setExplGovAncestor(fexplGovAncestor);
			}
			@Override
			public Object customize() throws Exception {
				// TODO Auto-generated method stub
				return null;
			}
		};
	}
}
